<script setup lang="ts">
  import routeComponentName from '@/config/route-component-name'
  import Pagination from '@/components/Pagination/index.vue'
  import useSparePartApplyListService from '@/services/module/store/useSparePartApplyListService'
  import { RefreshRight, Search } from '@element-plus/icons-vue'
  import { h, onMounted, ref, watch } from 'vue'
  import useOrganizeListService from '@/services/module/organize/useOrganizeListService'
  import { HMessage, HMessageBox } from '@/components/common/message'
  import { ElDivider, ElMessageBox, TableInstance } from 'element-plus'
  import { multipleDeleteSparePartApply } from '@/api/store'
  import { useRoute, useRouter } from 'vue-router'

  const { organizeList, getOrganizeListLoading, getOrganizeList } = useOrganizeListService()
  const {
    total,
    sparePartApplyList,
    getSparePartApplyListParam,
    getSparePartApplyListLoading,
    getSparePartApplyList,
    resetGetSparePartApplyListParam,
  } = useSparePartApplyListService()

  defineOptions({
    name: routeComponentName.storage.sparePartApply.list,
  })

  const router = useRouter()
  const route = useRoute()

  const paginationInstance = ref<InstanceType<typeof Pagination> | null>(null)
  const tableInstance = ref<TableInstance | null>(null)

  const allOrganize = ref<Array<OrganizeAPIResponse.OrganizeListListItem>>([])

  const selection = ref<Array<WarehouseAPIResponse.SparePartApplyListItem>>([])

  const dateRange = ref<Array<string>>([])

  const spacer = h(ElDivider, {
    direction: 'vertical',
    style: 'display: flex; align-items: center;',
  })

  const onResetClick = () => {
    dateRange.value.length = 0
    resetGetSparePartApplyListParam()
    getList()
  }

  const organizeListInit = async () => {
    await getOrganizeList()

    const getAllOrganize = (data: Array<OrganizeAPIResponse.OrganizeListListItem>) => {
      for (let i = 0; i < data.length; i++) {
        const organize = data[i]
        if (!organize.system) {
          allOrganize.value.push(organize)
        }
        getAllOrganize(data[i].organizesVos)
      }
    }

    getAllOrganize(organizeList.value)
  }

  const init = () => {
    getList()
    organizeListInit()
  }

  const handleDeleteClick = (data?: WarehouseAPIResponse.SparePartApplyListItem) => {
    if (!data && selection.value.some((item) => item.status !== 1)) {
      HMessageBox.error('只能删除待提交状态的配件申请单')
      return
    }

    if (data && tableInstance.value) {
      tableInstance.value.clearSelection()
      tableInstance.value.toggleRowSelection(data, true)
    }

    ElMessageBox({
      title: '提示',
      message: data ? '是否删除该配件申请单？' : '是否删除选中的配件申请单？',
      autofocus: false,
      showCancelButton: true,
      type: 'warning',
      async beforeClose(action, instance, done) {
        if (action === 'confirm') {
          try {
            instance.confirmButtonLoading = true
            instance.cancelButtonLoading = true
            const res = await multipleDeleteSparePartApply(selection.value.map((item) => item.id))
            instance.confirmButtonLoading = false
            instance.cancelButtonLoading = false
            if (res.data.code === 20000) {
              HMessage.success('操作成功')
              getList()
              done()
              return
            }

            HMessageBox.error(res.data.message)
            return
          } catch (error) {
            instance.confirmButtonLoading = false
            instance.cancelButtonLoading = false
          }
        }

        done()
      },
    })
  }

  const handleTableSelectionChange = (data: Array<WarehouseAPIResponse.SparePartApplyListItem>) => {
    selection.value = data
  }

  const handleDetailClick = (data: WarehouseAPIResponse.SparePartApplyListItem) => {
    if ([1, 4].includes(data.status)) {
      router.push(`/storage/spare/part/apply/update/${data.id}`)
    } else {
      router.push(`/storage/spare/part/apply/detail/${data.id}`)
    }
  }

  const onDateRangeChange = () => {
    if (dateRange.value && dateRange.value.length >= 1) {
      getSparePartApplyListParam.value.startTime = dateRange.value[0]
      getSparePartApplyListParam.value.endTime = dateRange.value[1]
      getList()
    }
  }

  const onDateRangeClear = () => {
    getSparePartApplyListParam.value.startTime = ''
    getSparePartApplyListParam.value.endTime = ''
    getList()
  }

  const getList = () => {
    if (paginationInstance.value) {
      getSparePartApplyListParam.value.limit = paginationInstance.value.size
      getSparePartApplyListParam.value.page = paginationInstance.value.current
      getSparePartApplyList()
    }
  }

  watch(
    () => route.path,
    () => {
      if (route.query.isUpdate === 'true') {
        getList()
      }
    },
  )

  onMounted(() => {
    init()
  })
</script>

<template>
  <div
    v-loading="getSparePartApplyListLoading || getOrganizeListLoading"
    class="spare-part-apply-list-page"
  >
    <div class="page-content">
      <div class="header">
        <div class="btn-group">
          <h-plain-button
            v-permission="'spareApply'"
            @click="router.push('/storage/spare/part/apply/create')"
          >
            申请配件
          </h-plain-button>
          <h-plain-button
            v-permission="'spareApplyDelete'"
            :disabled="selection.length <= 0"
            type="error"
            @click="handleDeleteClick(undefined)"
          >
            批量删除
          </h-plain-button>
        </div>
        <div class="search">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="到"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            clearable
            value-format="YYYY-MM-DD"
            @change="onDateRangeChange"
            @clear="onDateRangeClear"
          />
          <el-input
            v-model.trim="getSparePartApplyListParam.code"
            placeholder="请输入申请单编号"
            clearable
            style="width: 140px"
            @keyup.enter="getList"
            @clear="getList"
          />
          <el-input
            v-model.trim="getSparePartApplyListParam.networkName"
            placeholder="请输入经销商"
            clearable
            style="width: 140px"
            @keyup.enter="getList"
            @clear="getList"
          />
          <el-select
            v-model="getSparePartApplyListParam.status"
            placeholder="请选择状态"
            clearable
            style="width: 120px"
            @change="getList"
            @clear="getList"
          >
            <el-option :value="1" label="待提交" />
            <el-option :value="2" label="待审核" />
            <el-option :value="3" label="待过账" />
            <el-option :value="4" label="审核驳回" />
            <el-option :value="5" label="已过账" />
          </el-select>
          <h-button type="primary" @click="getList">
            <el-icon>
              <Search />
            </el-icon>
            搜索
          </h-button>
          <h-button @click="onResetClick">
            <el-icon>
              <RefreshRight />
            </el-icon>
            重置
          </h-button>
        </div>
      </div>
      <div class="table-pagination">
        <div class="table">
          <el-table
            ref="tableInstance"
            :border="true"
            :stripe="true"
            :resize="true"
            :data="sparePartApplyList"
            height="100%"
            @selection-change="handleTableSelectionChange"
          >
            <!-- 选择 -->
            <el-table-column type="selection" :align="'center'" fixed="left" width="50" />

            <!-- 序号 -->
            <el-table-column type="index" label="序号" :align="'center'" fixed="left" width="50" />

            <!-- 单号 -->
            <el-table-column label="单号" width="140" prop="code" show-overflow-tooltip>
              <template #default="{ row }">
                <h-link @click="handleDetailClick(row)">{{ row.code }}</h-link>
              </template>
            </el-table-column>

            <!-- 订单类型 -->
            <el-table-column label="订单类型" width="160">
              <template #default="{ row }">
                <template v-if="row.type === 1">收费销售订单</template>
                <template v-if="row.type === 2">免费销售订单</template>
                <template v-if="row.type === 3">免费销售订单(完全赠送)</template>
              </template>
            </el-table-column>

            <!-- 销售订单号 -->
            <el-table-column label="销售订单号" width="100" prop="saleNo" show-overflow-tooltip />

            <!-- 收货仓 -->
            <el-table-column
              label="收货仓"
              width="100"
              prop="receivingStoreName"
              show-overflow-tooltip
            />

            <!-- 经销商 -->
            <el-table-column label="经销商" width="200" prop="networkName" show-overflow-tooltip />

            <!-- 联系人 -->
            <el-table-column label="联系人" width="100" prop="contactName" show-overflow-tooltip />

            <!-- 联系人手机号 -->
            <el-table-column
              label="联系人手机号"
              width="120"
              prop="contactPhone"
              show-overflow-tooltip
            />

            <!-- 收货地址 -->
            <el-table-column label="收货地址" width="200" show-overflow-tooltip>
              <template #default="{ row }">
                {{
                  `${row.province || ''}${row.city || ''}${row.area || ''}${row.town || ''}${
                    row.detailAddress || ''
                  }`
                }}
              </template>
            </el-table-column>

            <!-- 制单人 -->
            <el-table-column label="制单人" min-width="100" show-overflow-tooltip prop="creator" />

            <!-- 审核人 -->
            <el-table-column label="审核人" width="100" show-overflow-tooltip prop="auditEmp" />

            <!-- 反写失败原因 -->
            <el-table-column label="反写失败原因" width="140" show-overflow-tooltip>
              <template #default="{ row }">
                <template v-if="row.isSync === 2">{{ row.failReason }}</template>
              </template>
            </el-table-column>

            <!-- 制单时间 -->
            <el-table-column label="制单时间" width="150" prop="createTime" />

            <!-- 最后更新时间 -->
            <el-table-column label="最后更新时间" width="150" prop="updateTime" />

            <!-- 配件单状态 -->
            <el-table-column label="配件单状态" width="100" fixed="right">
              <template #default="{ row }">
                <h-status v-if="row.status === 1">待提交</h-status>
                <h-status v-if="row.status === 2" type="warning">待审核</h-status>
                <h-status v-if="row.status === 3" type="warning">待过账</h-status>
                <h-status v-if="row.status === 4" type="error">审核驳回</h-status>
                <h-status v-if="row.status === 5">已过账</h-status>
              </template>
            </el-table-column>

            <!-- 反写状态 -->
            <el-table-column label="反写状态" width="140" fixed="right">
              <template #default="{ row }">
                <h-status v-if="row.isSync === 0" type="warning">待反写</h-status>
                <h-status v-if="row.isSync === 1">{{ `${row.syncType}成功` }}</h-status>
                <h-status v-if="row.isSync === 2" type="error">{{
                  `${row.syncType}失败`
                }}</h-status>
              </template>
            </el-table-column>

            <!-- 操作 -->
            <el-table-column label="操作" width="100" fixed="right">
              <template #default="{ row }">
                <el-space :size="0" :spacer="spacer">
                  <h-link @click="handleDetailClick(row)">详情</h-link>
                  <h-link
                    v-if="row.status === 1"
                    v-permission="'spareApplyDelete'"
                    type="error"
                    @click="handleDeleteClick(row)"
                  >
                    删除
                  </h-link>
                  <h-link v-else v-permission="'spareApplyDelete'" disabled>删除</h-link>
                </el-space>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="pagination">
          <Pagination
            ref="paginationInstance"
            :list_total="total"
            @current-change="getList"
            @page-size="getList"
          />
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped lang="scss">
  .spare-part-apply-list-page {
    box-sizing: border-box;
    width: 100%;
    height: calc(100vh - 92px);
    padding: 12px;

    .page-content {
      width: 100%;
      height: 100%;
      background-color: #fff;
      box-sizing: border-box;
      padding: 12px;
      display: flex;
      flex-direction: column;
      row-gap: 12px;

      .header {
        display: flex;
        justify-content: space-between;

        .btn-group {
          display: flex;
          column-gap: 4px;
        }

        .search {
          display: flex;
          column-gap: 4px;
        }
      }

      .table-pagination {
        flex: 1;
        height: 0;
        display: flex;
        flex-direction: column;
        row-gap: 12px;

        .table {
          max-height: calc(100% - 40px);
        }

        .pagination {
          display: flex;
          justify-content: flex-end;
        }
      }
    }
  }

  :deep(.el-date-editor) {
    height: 28px;
    width: 230px;
  }
</style>
